package com.example.okhttp;

import android.util.Log;

import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class RequestUtils {
    public static final String requestGet = "GET";
    public static final String requestPost = "POST";

    /**
     * GET请求
     *
     * @param url
     */
    public static void sendRequest(String url) {
        OkHttpClient client = new OkHttpClient();
         Request request = new Request.Builder()
                .url(url)
                .header("Content-Type", "application/json;charset=utf-8")
                .get()
                .build();
        client.newCall(request).enqueue(new Callback() {
            /*请求失败*/
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("DeBug", "onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
               Log.e("DeBug", "onSuccess: " + response.body().string());

            }
        });

    }

    /**
     * POST请求
     *
     * @param url
     * @param
     */
    public static void sendRequest(String url, JSONObject data) {
        RequestBody body = FormBody.create(MediaType.parse("application/json"), data.toString());
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e("DeBug", "onFailure: " + e.getMessage());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                   Log.e("DeBug", "onSuccess: " + response.body().string());

                }
            });
    }
}